package hero.mps.web.school_student.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import hero.mps.utils.ResultUtils;
import hero.mps.utils.ResultVo;
import hero.mps.web.role_stu.entity.StuRole;
import hero.mps.web.role_stu.service.StuRoleService;
import hero.mps.web.school_class.entity.SchoolClass;
import hero.mps.web.school_class.service.SchoolClassService;
import hero.mps.web.school_student.entity.*;
import hero.mps.web.school_student.service.SchoolStudentService;
import hero.mps.web.sys_role.entity.SysRole;
import hero.mps.web.sys_role.service.SysRoleService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/student")
@AllArgsConstructor
public class StudentController {
    private final SchoolStudentService schoolStudentService;
    private final SchoolClassService schoolClassService;
    private final SysRoleService sysRoleService;
    private final StuRoleService stuRoleService;

    /**
     * 获取学生数量统计信息
     *
     */
    @GetMapping("/getStuCount")
    public ResultVo getStuCount() {
        StuCount stuCount = schoolStudentService.getStuCount();
        return ResultUtils.success("查询成功", stuCount);
    }

    /**
     * 获取热门专业的信息
     *
     */
    @GetMapping("/getHotMajor")
    public ResultVo getHotMajor() {
        List<HotMajorVO> hotMajor = schoolStudentService.getHotMajor();
        return ResultUtils.success("查询成功", hotMajor);
    }
    /**
     * 导入学生成绩
     */
    @PostMapping("importStuInfo")
    public ResultVo importStuInfo(@RequestParam("file") MultipartFile file, Integer classId, String intoTime) throws Exception{
        ImportParams importParams = new ImportParams();
        // 数据处理
        importParams.setHeadRows(1);
        ExcelImportResult<StuExcel> result = ExcelImportUtil.importExcelMore(file.getInputStream(), StuExcel.class, importParams);
        List<StuExcel> list = result.getList();
        if (list.size() == 0) {
            return ResultUtils.error("导入失败,请检查文件格式");
        }
        //查询学生角色id
        LambdaQueryWrapper<SysRole> queryWrapper = Wrappers.lambdaQuery(SysRole.class)
                .eq(SysRole::getRoleType, "2");
        SysRole sysRole = sysRoleService.getOne(queryWrapper);
        if (sysRole == null) {
            return ResultUtils.error("请先创建学生角色");
        }
        if (list.size() >= 0) {
            for (int i = 0; i < list.size(); i++) {
                SchoolStudent schoolStudent = new SchoolStudent();
                BeanUtils.copyProperties(list.get(i), schoolStudent);
                schoolStudent.setRoleId(sysRole.getRoleId());
                schoolStudent.setClassId(classId);
                schoolStudent.setIntoTime(intoTime);
                schoolStudent.setPassword(DigestUtils.md5DigestAsHex("666666".getBytes()));
                schoolStudent.setStuNum(intoTime.replace("-", "") + intoTime.split("-")[0] + String.format("%03d", i+1));
                schoolStudentService.saveStu(schoolStudent);
            }
        }
        return ResultUtils.success("导入成功");
    }
    private static String generateStuNum(String intoTime, int seqNumber) {
        return intoTime.replace("-", "") + String.format("%03d", seqNumber);
    }
    /**
     * 导出班级学生信息
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/importStuTemplate")
    public ResultVo importStuTemplate (HttpServletResponse response) throws IOException {

        ArrayList<StuExcel> list = new ArrayList<>();
        String fileName = "学生信息模版.xlsx";
        ExportParams exportParams = new ExportParams();
        exportParams.setType(ExcelType.XSSF);
        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, StuExcel.class, list);
        downloadExcel(fileName, sheets, response);
        return ResultUtils.success("导出成功");
    }

    @RequestMapping("/exportStuInfo")
    public ResultVo exportStuInfo (HttpServletResponse response, Integer classId) throws IOException {
        // 查询班级信息
        SchoolClass schoolClass = schoolClassService.getById(classId);
        // 查询班级下的所有学生
        LambdaQueryWrapper<SchoolStudent> queryWrapper = Wrappers.lambdaQuery(SchoolStudent.class)
                .eq(SchoolStudent::getClassId, schoolClass.getClassId());
        List<SchoolStudent> studentList = schoolStudentService.list(queryWrapper);
        ArrayList<StuExcel> list = new ArrayList<>();
        // 导出excel
        for (int i = 0; i < studentList.size(); i++) {
            StuExcel excel = new StuExcel();
            BeanUtils.copyProperties(studentList.get(i), excel);
            list.add(excel);
        }
        String fileName = schoolClass.getClassName() + "学生信息.xlsx";
        ExportParams exportParams = new ExportParams();
        exportParams.setType(ExcelType.XSSF);
        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, StuExcel.class, list);
        downloadExcel(fileName, sheets, response);
        return ResultUtils.success("导出成功");
    }

    public static void downloadExcel(String fileName, Workbook workbook, HttpServletResponse response) throws IOException {
        try {
            if (StringUtils.isEmpty(fileName)) { // 假设StringUtils是Apache Commons Lang库中的类
                throw new RuntimeException("导出文件名不能为空");
            }

            String encodeFileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-Type", "application/vnd.ms-excel; charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + encodeFileName); // 修正filename格式
            response.setHeader("FileName", encodeFileName); // 通常这个header不是标准的，但在某些情况下可能被前端使用
            response.setHeader("Access-Control-Expose-Headers", "FileName"); // 允许跨域访问这个header

            workbook.write(response.getOutputStream()); // 修正方法名为getOutputStream
            workbook.close();
        } catch (Exception e) {
            try {
                workbook.close(); // 确保在异常时关闭Workbook
            } catch (IOException ex) {
                // 可以在这里记录日志或者进行其他异常处理
            }
            throw e; // 重新抛出异常，以便上层可以处理
        }
    }

    /**
     * 重置学生密码
     *
     * @param schoolStudent 学生对象，包含学生ID和密码信息
     */
    @PostMapping("/resetPassword")
    public ResultVo resetPassword(@RequestBody SchoolStudent schoolStudent) {
        schoolStudent.setPassword(DigestUtils.md5DigestAsHex(schoolStudent.getPassword().getBytes()));
        boolean b = schoolStudentService.updateById(schoolStudent);
        if (b) {
            return ResultUtils.success("重置成功");
        }else {
            return ResultUtils.error("重置失败");
        }
    }
    /**
     * 新增学生信息
     * @param schoolStudent
     * @return
     */
    @PostMapping
    public ResultVo add(@RequestBody SchoolStudent schoolStudent) {
        LambdaQueryWrapper<SchoolStudent> queryWrapper = Wrappers.lambdaQuery(SchoolStudent.class).eq(SchoolStudent::getStuNum, schoolStudent.getStuNum());
        SchoolStudent one = schoolStudentService.getOne(queryWrapper);
        if (one != null) {
            return ResultUtils.error("该学生学号已存在");
        }
        schoolStudent.setPassword(DigestUtils.md5DigestAsHex(schoolStudent.getPassword().getBytes()));
        schoolStudentService.saveStu(schoolStudent);
        return ResultUtils.success("新增成功");
    }

    /**
     * 编辑学生信息
     * @param schoolStudent
     * @return
     */
    @PutMapping
    public ResultVo edit(@RequestBody SchoolStudent schoolStudent) {
        LambdaQueryWrapper<SchoolStudent> queryWrapper = Wrappers.lambdaQuery(SchoolStudent.class).eq(SchoolStudent::getStuNum, schoolStudent.getStuNum());
        SchoolStudent one = schoolStudentService.getOne(queryWrapper);
        if (one != null && !one.getStuId().equals(schoolStudent.getStuId())) {
            return ResultUtils.error("该学生学号已存在");
        }
        schoolStudent.setPassword(DigestUtils.md5DigestAsHex(schoolStudent.getPassword().getBytes()));
        schoolStudentService.updateStu(schoolStudent);
        return ResultUtils.success("编辑成功");
    }

    /**
     * 根据学生id删除学生信息
     * @param stuId
     * @return
     */
    @DeleteMapping("/{stuId}")
    public ResultVo delete(@PathVariable("stuId") Integer stuId) {
        schoolStudentService.deleteStu(stuId);
        return ResultUtils.success("删除成功");
    }

    /**
     * 根据学生id查询学生信息
     * @param stuId
     * @return
     */
    @GetMapping("/getById")
    public ResultVo getById(Integer stuId) {
        SchoolStudent stu = schoolStudentService.getStuById(stuId);
        return ResultUtils.success("查询成功", stu);
    }

    /**
     * 查询学生信息列表
     * @param studentParam
     * @return
     */
    @GetMapping("/getList")
    public ResultVo getList(StudentParam studentParam) {
        IPage<SchoolStudent> list = schoolStudentService.getList(studentParam);
        return ResultUtils.success("查询成功", list);
    }

    /**
     * 查询学生可成列表
     * @param courseParamVO
     * @return
     */
    @GetMapping("/getCourseList")
    public ResultVo getCourseList(CourseParamVO courseParamVO) {
        IPage<MyCourseVO> list = schoolStudentService.getCourseList(courseParamVO);
        return ResultUtils.success("查询成功", list);
    }

    /**
     * 根据专业id查询班级
     * @param majorId
     * @return
     */
    @GetMapping("/getClass")
    public ResultVo getClass(Integer majorId) {
//        构建查询条件
        QueryWrapper<SchoolClass> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SchoolClass::getMajorId, majorId);
        List<SchoolClass> list = schoolClassService.list(queryWrapper);
        return ResultUtils.success("查询成功", list);
    }

    /**
     * 获取角色列表
     * @return
     */
    @GetMapping("/getRoles")
    public ResultVo getRole() {
//        构建查询条件
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysRole::getRoleType, "2");
        List<SysRole> list = sysRoleService.list(queryWrapper);
        return ResultUtils.success("查询成功", list);
    }

    /**
     * 获取角色列表
     * @return
     */
    @GetMapping("/getRoleId")
    public ResultVo getRoleId(Integer stuId) {
//        构建查询条件
        QueryWrapper<StuRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(StuRole::getStuId, stuId);
        StuRole stuRole = stuRoleService.getOne(queryWrapper);
        return ResultUtils.success("查询成功", stuRole);
    }

}
